<?php
function webSockets($address, $port) {
    global $users;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
    socket_bind($socket, $address, $port);
    socket_listen($socket);
    $socks = array(
        $socket
    );
    while (true) {
        $changes = $socks;
        $write = $except = NULL;
        try{
        socket_select($changes, $write, $except, NULL);
        }catch(Exception $e){
            echo $e->getMessage();
        }
        foreach ($changes as $sign) {
            if ($socket == $sign) {
                $msgsock = socket_accept($socket);
                $socks[] = $msgsock;
                $users[] = array(
                    'socket'=>$msgsock,
                    'hand' => false
                );
                //$buf1 = socket_read($msgsock,1024);
                //echo "Received msg: $buf1   \n";
                //handshake($buf1, $msgsock);
                
            } else {
                try{
                $len=@socket_recv($sign, $buffer1, 2048, 0);
                }catch(Exception $e){
                    echo $e->getMessage();
                    
                }
                
                $msg = decodestr($buffer1);
                $sevmsg = @iconv('utf-8', 'gbk//IGNORE', $msg);
                echo $sevmsg . "\n";
                socket_getpeername($sign,$address,$port);
                //echo $address.$port;
                date_default_timezone_set('PRC');
                $msg='客户：'.$port.' 内容：'.$msg;
                $msg=$msg.' 发送时间：'.date("Y-m-d H:i:s");
                try{
                $k=indexI($sign);
                }catch(Exception $e){echo $e->getMessage();}
                if($len<7){
                    socket_close($sign);
                    unset($users[$k]);
                    unset($socks[$k]);
                    //unset($changes[$k]);
                    //continue;
                    
                }
                
                $msg = encodestr($msg);
                try{
                if (!$users[$k]['hand']) {
                    handshake($buffer1, $msgsock,$k);
                } else {
                    foreach ($users as $user) {
                        //if ($users[$k]['hand']) {
                            socket_write($user['socket'], $msg, strlen($msg));
                        //}
                    }
                }
                //$msg=@iconv('utf-8','gbk//IGNORE',$msg);
                //socket_write($sign,$msg,strlen($msg));
            }catch(Exception $e){echo $e->getMessage();}
                
            }
        
            //socket_send($sign,$msg,strlen($msg),MSG_OOB);
            //foreach ($socks as  $values){
            //socket_write($values,$msg,strlen($msg));
            //}
            
        }
    }
}
$users = array();
webSockets("192.168.0.0", 8000);

function handshake($buffer, $msgsock,$k) {
    global $users;
    $buf = substr($buffer, strpos($buffer, 'Sec-WebSocket-Key:') + 18);
    $key = trim(substr($buf, 0, strpos($buf, "\r\n")));
    $new_key = base64_encode(sha1($key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
    $new_message = "HTTP/1.1 101 Switching Protocols\r\n";
    $new_message.= "Upgrade: websocket\r\n";
    $new_message.= "Sec-WebSocket-Version: 13\r\n";
    $new_message.= "Connection: Upgrade\r\n";
    $new_message.= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
    socket_write($msgsock, $new_message, strlen($new_message));
    $users[$k]['hand'] = true;
}
function decodestr($text) {
    $length = ord($text[1]) & 127;
    if ($length == 126) {
        $masks = substr($text, 4, 4);
        $data = substr($text, 8);
    } elseif ($length == 127) {
        $masks = substr($text, 10, 4);
        $data = substr($text, 14);
    } else {
        $masks = substr($text, 2, 4);
        $data = substr($text, 6);
    }
    $text = "";
    for ($i = 0; $i < strlen($data); ++$i) {
        $text.= $data[$i] ^ $masks[$i % 4];
    }
    return $text;
}
function encodestr($text) {
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);
    if ($length <= 125) $header = pack('CC', $b1, $length);
    elseif ($length > 125 && $length < 65536) $header = pack('CCn', $b1, 126, $length);
    elseif ($length >= 65536) $header = pack('CCNN', $b1, 127, $length);
    return $header . $text;
}
function indexI($v){
    global $users;
    foreach($users as $k=>$va){
        if($va['socket']==$v)
        return $k;
    }
}
?>  
